package com.hc.server.conn.bill;

import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;

import com.hc.server.Config;
import com.hc.server.util.HttpConnect;

public class BillServerHelper {

	private static final String I_SEND_BILL_BY_PHONE = "I_SEND_BILL_BY_PHONE";

	private static final String TRANS_ID = "TRANS_ID";
	private static final int transId = 69;// FIXME:待分配
	private static final String PHONE = "PHONE";
	private static final String AMOUNT = "AMOUNT";
	// private static final String CURRENCY = "CURRENCY";
	private static final String THIRD_ID = "THIRD_ID";
	private static final String THIRD_STATUS = "THIRD_STATUS";
	// private static final String BOLISH_TIME = "BOLISH_TIME";
	private static final String VALID_PERIOD = "VALID_PERIOD";
	private static final String DESCRIPTION = "DESCRIPTION";
	// private static final String ADDITION = "ADDITION";
	private static final String IS_UNIQUE = "IS_UNIQUE";

	/**
	 * 
	 * @param orderId
	 * @param phone
	 * @param amount
	 * @param des
	 * @return BillResponse
	 * @throws JSONException 
	 * @throws IOException 
	 */
	public static BillResponse createBill(String orderId, String phone, int amount,
			String des) throws IOException, JSONException {
		BillRequest req = new BillRequest();

		req.setActionName(I_SEND_BILL_BY_PHONE);
		req.put(TRANS_ID, transId);
		req.put(PHONE, phone);
		req.put(AMOUNT, amount);
		// req.put(CURRENCY, value);//不设置币种，缺省为中文
		req.put(THIRD_ID, orderId);
		req.put(THIRD_STATUS, "new");// TODO：有什么用？
		// req.put(BOLISH_TIME, value);//FIXME：不设置具体的失效时间，避免双方系统时间不对
		req.put(VALID_PERIOD, 5);// 5分钟有效期
		req.put(DESCRIPTION, des);
		// req.put(ADDITION, value);//FIXME：没有附加信息
		req.put(IS_UNIQUE, "yes");

		BillResponse resp = post2BillServer(req);
		return resp;
	}

	private static BillResponse post2BillServer(BillRequest req) throws IOException, JSONException {
		HttpConnect conn = null;
		BillResponse resp = null;
		try {
			conn = new HttpConnect(Config.BILL_SERVER_URL);
			conn.SendData(req.toString());
			String respMsg = conn.ReceiveUTFString();
			resp = BillResponse.parser(respMsg);		
		}catch (MalformedURLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.releaseHttpConnect();
			}
		}
		return resp;
	}
}
